<!DOCTYPE html>
<html>
<head lang="en">
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    <title>Javascript 返回顶部</title>
    <style type="text/css">
        #btn {
            width: 40px;
            height: 40px;
            position: fixed;
            right: 65px;
            bottom: 10px;
            display: none;
            background: url(images/top_bg.png) no-repeat left top;
        }

        #btn:hover {
            background: url(images/top_bg.png) no-repeat 0 -39px;
        }

        .bg {
            width: 1190px;
            margin: 0 auto;
        }
    </style>

</head>
<body>
<a href="javascript:;" id="btn" title="回到顶部"></a>

<div class="bg">
    <img src="images/tb_bg.jpg" alt=""/>
</div>

<script>
    window.onload = function () {
        var obtn = document.getElementById('btn'),
                clientHeight = document.documentElement.clientHeight,
                timer = null,
                isTop = true;
        window.onscroll = function () {
            var osTop = document.documentElement.scrollTop || document.body.scrollTop;
            if(osTop>= clientHeight){
                obtn.style.display = 'block';
            }else{
                obtn.style.display = 'none';
            }
            if (!isTop) clearInterval(timer);
            isTop = false;
        };
        obtn.onclick = function () {
            if(!isTop){
                timer = setInterval(function () {
                    var osTop = document.documentElement.scrollTop || document.body.scrollTop;
                    var ispeed = Math.floor(-osTop / 5);
                    document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed;
                    isTop = true;
                    if (osTop == 0) clearInterval(timer);
                }, 30);
            }
        };
    };
</script>
</body>
</html>